<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/6/8
 */

namespace app\educational\model;


use think\Db;
use think\Model;

class MessageModel extends Model
{
    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    /**
     * 获取消息列表
     * @param array $filter
     * @param array $order
     * @param int $limit
     * @param $query
     * @return \think\Paginator
     */
    public function getMessages($filter=[], $order=[], $limit=10, $query)
    {
        //默认条件
        $where = [
            'm.create_time' => ['>=', 0],
            'm.delete_time' => ['=', 0],
        ];
        if(!empty($filter) && is_array($filter)){
            $where = array_merge($where,$filter);
        }

        //默认排序
        $sort = ['m.id'=>'desc'];
        if(!empty($order) && is_array($order)){
            $sort = array_merge($order,$sort);
        }

        //分页url额外参数
        $page_query['query'] = [];
        if(!empty($query) && is_array($query)){
            $page_query['query'] = $query;
        }

        $data = $this->alias('m')
            ->field('m.*,mu.id as mu_id,mu.receive_uid,mu.msg_status,mu.delete_time as dtime,u.realname as user_name,nu.realname as receive_name')
            ->join('user u','m.send_uid=u.id')
            ->join('message_user mu','m.id=mu.msg_id','left')
            ->join('user nu','mu.receive_uid=nu.id','left')
            ->where($where)
            ->order($sort)
            ->paginate($limit,false,$page_query);

        return $data;
    }

    /**
     * 发送消息
     * @param array $data
     * @param array $uid 发送者(二维数组)
     * @return bool|int|string
     */
    public function sendMsg($data=[], $uid=[])
    {
        if(empty($data) || empty($uid)){
            return false;
        }

        self::startTrans();
        try{
            //保存消息
            $id = $this->allowField(true)->insertGetId($data);
            foreach($uid as $key=>$value){
                //发送消息
                $new_data['msg_id'] = $id;
                $new_data['receive_uid'] = $value['id'];
                $new_data['msg_status'] = 0;//未读

                Db::name('message_user')->insert($new_data);
            }
            self::commit();
            $result = $id;

        }catch(\Exception $e){
            self::rollback();
            $result = false;
        }
        return $result;
    }

    /**
     * 发送邮件
     * @param array $data
     * @param array $email
     * @return bool|int|string
     */
    public function sendEmail($data=[], $email=[], &$msg='')
    {
        if(empty($data) || empty($email)){
            $msg = '参数有误';
            return false;
        }

        self::startTrans();
        try{
            //保存消息
            $id = $this->allowField(true)->insertGetId($data);
            //发送邮件
            $address = $email;
            $subject = trim($data['subject']);
            $content = trim($data['content']);
            $res = cmf_send_email($address,$subject,$content);
            if ($res['error'] == 1) {
                $msg = $res['message'];
                $result = false;
                exception('邮件发送失败');
            }else{
                $result = $id;
            }

            self::commit();

        }catch(\Exception $e){
            self::rollback();
            $result = false;
        }
        return $result;
    }

    /**
     * 编辑消息
     * @param array $data
     * @return bool
     */
    public function editMsg($data=[])
    {
        $result = true;
        $id = intval($data['id']);

        $oldScore = $this->where('id', $id)->find();
        if(!isset($oldScore->id)){
            $result = false;
        }else{
            self::startTrans();
            try{
                $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

                self::commit();
            }catch(\Exception $e){
                self::rollback();
                $result = false;
            }
        }

        return $result;
    }

    /**
     * @param $id
     * @param $cur_time
     * @return bool
     */
    public function deleteMsg($id, $cur_time)
    {
        $result = true;
        if(empty($id)){
            $result = false;
        }else{
            if(empty($cur_time)){
                //当前时间
                $cur_time = time();
            }
            if(is_array($id)){
                //批量删除
                self::startTrans();
                try{
                    $this->where(['id' => ['in', $id]])->update(['delete_time'=>$cur_time]);
                    Db::name('message_user')->where(['msg_id' => ['in', $id]])->update(['delete_time'=>$cur_time]);

                    self::commit();
                }catch(\Exception $e){
                    self::rollback();
                    $result = false;
                }
            }else{
                //单一删除
                self::startTrans();
                try{
                    $this->where(['id' => $id])->update(['delete_time'=>$cur_time]);
                    Db::name('message_user')->where(['msg_id' => $id])->update(['delete_time'=>$cur_time]);

                    self::commit();
                }catch(\Exception $e){
                    self::rollback();
                    $result = false;
                }
            }
        }

        return $result;
    }

}